package cc.linker.steplink.crm.merchanth5.service;

import cc.linker.steplink.crm.commons.enums.IntegralEnums;
import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.integral.IntegralRequest;
import cc.linker.steplink.crm.commons.yzj.YzjRequest;
import cc.linker.steplink.crm.commons.yzj.YzjPointPo;
import cc.linker.steplink.crm.merchanth5.dao.CustomerIntegralDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: CKQ
 * @DateTime: 2020/9/27 19:28
 * @Description: TODO
 */
@Slf4j
@Service
public class CustomerIntegralService {

    @Autowired
    private IntegralRequest integralRequest;
    @Autowired
    private CustomerIntegralDao customerIntegralDao;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private YzjRequest yzjRequest;
    @Lazy
    @Autowired
    private VipCustomerLogService vipCustomerLogService;

    /**
     * @Description：获取积分服务中的用户信息
     * @DateTime：2020/9/11 9:48
     * @Params：
     * @Return：
     */
    public Map<String, Object> getIntegralCustomerInfo(String customerId, String orgId) {
        Map<String, Object> params = new HashMap<>();
        params.put("customerId", customerId);
        Map<String, Object> stringObjectMap = this.integralRequest.doRequest("get-customer-info", params);
        String sourceUserId = customerIntegralDao.getSourceUserId(customerId);
        if (!StringUtils.isEmpty(sourceUserId) && yzjRequest.yzjOrgId.equals(orgId)) {
            String customerPoint = this.yzjRequest.queryMemberPoint(sourceUserId);
            stringObjectMap.put("customerScore", customerPoint);
        }
        return stringObjectMap;
    }

    /**
     * @Description：获取本系统积分服务中的用户信息
     * @DateTime：2020/9/11 9:48
     * @Params：
     * @Return：
     */
    public Map<String, Object> getCrmIntegralCustomerInfo(String customerId) {
        Map<String, Object> params = new HashMap<>();
        params.put("customerId", customerId);
        Map<String, Object> stringObjectMap = this.integralRequest.doRequest("get-customer-info", params);
        return stringObjectMap;
    }

    /**
     * @param customerId        用户Id
     * @param orgId             机构ID 可为空
     * @param integralFieldName 积分属性字段（enums枚举下的用户积分或用户成长值或许有增加可用其他）
     * @param pageIndex         当前第几页
     * @param pageSize          每页多少条
     * @Description：获取积分用户日志记录
     * @DateTime：2020/9/11 9:54
     * @Params：
     * @Return：
     */
    public Map<String, Object> getIntegralCustomerLogs(String customerId, String orgId, String integralFieldName, Integer pageIndex, String sourceFieldName, Integer pageSize) {
        Map<String, Object> params = new HashMap<>();
        params.put("customerId", customerId);
        params.put("orgId", orgId);
        params.put("integralFieldName", integralFieldName);
        params.put("sourceFieldName", sourceFieldName);
        params.put("pageIndex", pageIndex);
        params.put("pageSize", pageSize);
        return this.integralRequest.doRequest("get-customer-logs", params);
    }

    /**
     * @param customerId        用户ID
     * @param behavior          用户行为比如：购买了XXXXXXXXXX商品
     * @param integralFieldName 积分属性名称
     * @param score             增减的积分
     * @param sourceFieldName   来源属性名称
     * @param orgId             机构ID
     * @Description：添加用户积分（包含雅智捷）
     * @DateTime：2020/9/11 10:04
     * @Params：
     * @Return：
     */
    public void addIntegralCustomerLog(String customerId, String behavior, String integralFieldName, String score, String sourceFieldName, String orgId) {
        Map<String, Object> params = new HashMap<>();
        params.put("customerId", customerId);
        params.put("orgId", orgId);
        params.put("behavior", behavior);
        params.put("integralFieldName", integralFieldName);
        params.put("score", score);
        params.put("sourceFieldName", sourceFieldName);
        String sourceUserId = customerIntegralDao.getSourceUserId(customerId);
        if (this.yzjRequest.yzjOrgId.equals(orgId) && !integralFieldName.equals(IntegralEnums.customerGrowthScore.toString())) {
            if (!StringUtils.isEmpty(sourceUserId)) {
                YzjPointPo yzjPointPo = new YzjPointPo();
                yzjPointPo.setCustomerId(sourceUserId);
                int integerScore = Integer.parseInt(score);
                if (integerScore > 0) {
                    yzjPointPo.setActionTypeCode("add");
                } else {
                    yzjPointPo.setActionTypeCode("deduct");
                    integerScore = integerScore * -1;
                }
                yzjPointPo.setPointAmount(integerScore);
                yzjPointPo.setRemark(behavior);
                this.yzjRequest.adjustMemberPoint(yzjPointPo);
                return;
            }
        }
        this.integralRequest.doRequest("add-customer-log", params);
        if (IntegralEnums.customerGrowthScore.toString().equals(integralFieldName)) {
            this.upateCustomerLevel(customerId, orgId, sourceUserId, score);
        }
    }

    /**
     * 调整本系统用户积分
     *
     * @param customerId
     * @param behavior
     * @param integralFieldName
     * @param score
     * @param sourceFieldName
     * @param orgId
     */
    public void adjustIntegralCustomerLog(String customerId, String behavior, String integralFieldName, String score, String sourceFieldName, String orgId, String sourceUserId) {
        Map<String, Object> params = new HashMap<>();
        params.put("customerId", customerId);
        params.put("orgId", orgId);
        params.put("behavior", behavior);
        params.put("integralFieldName", integralFieldName);
        params.put("score", score);
        params.put("sourceFieldName", sourceFieldName);
        this.integralRequest.doRequest("add-customer-log", params);
        if (IntegralEnums.customerGrowthScore.toString().equals(integralFieldName)) {
            this.upateCustomerLevel(customerId, orgId, sourceUserId, score);
        }
    }


    /**
     * @param integralFieldName 积分字段
     * @param startScore        开始积分
     * @param endScore          结束积分
     * @Description：通过分数区间获取用户ID列表
     * @DateTime：2020/9/27 17:23
     * @Params：
     * @Return：
     */
    public Map<String, Object> getCustomerIdsByIntegral(String integralFieldName, Long startScore, Long endScore,String orgId) {
        Map<String, Object> params = new HashMap<>();
        params.put("fieldName", integralFieldName);
        params.put("startScore", startScore);
        params.put("endScore", endScore);
        params.put("orgId", orgId);
        return this.integralRequest.doRequest("get-customer-ids", params);
    }

    /**
     * @Description：批量更新用户的等级
     * @DateTime：2021/1/21 15:25
     * @Params：
     * @Return：
     */
    public void setCustomersLevelId(Long startScore, Long endScore, String levelId,String orgId) {
        Map<String, Object> result = this.getCustomerIdsByIntegral(IntegralEnums.customerGrowthScore.toString(), startScore, endScore, orgId);
        if (result.containsKey("customerIds") && result.get("customerIds") != null) {
            List<String> customerIds = (List) result.get("customerIds");
            if (customerIds != null && customerIds.size() > 0) {
                this.customerIntegralDao.updateCustomersLevelId(customerIds, levelId, orgId);
            }
        }
    }

    /**
     * @Description：查询用户的积分数据列表
     * @DateTime：2021/1/19 14:54
     * @Params：
     * @Return：
     */
    public List<Map<String, Object>> getCustomersScore(Map<String, Object> params) {
        Map<String, Object> result = this.integralRequest.doRequest("get-customers-score", params);
        if (result.containsKey("data") && result.get("data") != null) {
            return (List) result.get("data");
        }
        return null;
    }

    /**
     * @Description：编辑用户积分
     * @DateTime：2020/9/27 19:41
     * @Params：
     * @Return：
     */
    @Async
    public void upateCustomerLevel(String customerId, String orgId, String soureceUserId, String score) {
        int old = 0;
        Map<String, Object> integralMap = this.getIntegralCustomerInfo(customerId, orgId);
        if (integralMap != null) {
            Integer growScore = (Integer) integralMap.get(IntegralEnums.customerGrowthScore.toString());
            if(growScore==null){
                growScore = 0;
            }
            Integer changeScore = growScore;
            if (score != null) {
                changeScore = Integer.parseInt(score);
            }
            String levelId = this.customerIntegralDao.getLevelId(orgId, growScore);
            this.customerIntegralDao.updateCustomerLevel(levelId, customerId);
            this.yzjRequest.alterMemberLevel(soureceUserId, "", levelId, orgId);
            if (growScore >= 0) {
                old = growScore - changeScore;
                if (old > 0) {
                    vipCustomerLogService.growthOpenAccount(customerId, orgId, Long.parseLong(Integer.toString(old)), null);
                }
            }
        }else {
            Integer growScore = 0;
            String levelId = this.customerIntegralDao.getLevelId(orgId, growScore);
            this.customerIntegralDao.updateCustomerLevel(levelId, customerId);
        }
    }
}
